#!/usr/bin/env python
#-*- coding: utf-8 -*-
import os
import time
import re
import requests
import urllib
from flask import current_app
from fx.lib.utils import get_random_string, compatmd5
from fx.utils.timeutil import get_now_str, datetime_to_str_time, get_now


ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])

UserAgent = ('Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 '
             '(KHTML, like Gecko) Chrome/32.0.1700.76 Safari/537.36')

HUMAN_HEADERS = {
    'Accept': ('text/html,application/xhtml+xml,application/xml;'
               'q=0.9,image/webp,*/*;q=0.8'),
    'User-Agent': UserAgent,
    'Accept-Encoding': 'gzip,deflate,sdch'
}


def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


def save_upload_file(file):
    upload_folder = current_app.config['UPLOAD_FOLDER']
    filename = file.filename
    if not allowed_file(filename):
        return ''
    file_suffix = os.path.splitext(filename)[-1].lower()
    new_filename = datetime_to_str_time(get_now(), format_str='%Y%m%d%H%M%S')
    s_filename = compatmd5(
        get_random_string() + new_filename + get_random_string()) + file_suffix
    print s_filename
    month = get_now_str(format_str='%Y%m') + '/'
    upload_folder = upload_folder + month
    if not os.path.exists(upload_folder):
        os.makedirs(upload_folder)
    file.save(os.path.join(upload_folder, s_filename))
    return month + s_filename


def get_upload_file_url(path):
    return current_app.config['IMAGES_DOMAIN'] + path


def save_upload_by_url(url):
    try:
        u = requests.get(url, headers=HUMAN_HEADERS, timeout=10)
    except:
        return ''

    if u.status_code == 200:
        image_type = u.headers.get('Content-Type', '')
        image_type = re.split('[;,]', image_type)[0]
        image_type = image_type.replace('image/', '').lower()
        if not image_type:
            image_type = 'jpeg'
        if image_type not in ALLOWED_EXTENSIONS:
            image_type = 'jpeg'
        s_filename = compatmd5(get_random_string() + str(time.time())) + '.' + image_type
        upload_folder = current_app.config['UPLOAD_FOLDER']
        month = get_now_str(format_str='%Y%m') + '/'
        upload_folder = upload_folder + month
        if not os.path.exists(upload_folder):
            os.makedirs(upload_folder)
        urllib.urlretrieve(url, os.path.join(upload_folder, s_filename))
        return month + s_filename
    else:
        return ''
